package com.syedu.cels.dao.impl;

import com.syedu.cels.dao.BaseDao;
import com.syedu.cels.entity.Vocabulary;
import com.syedu.cels.entity.Word;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import static com.syedu.cels.constants.IConstants.VOCABULARY_FILE_PATH;
import static com.syedu.cels.constants.IConstants.WORD_FILE_PATH;

/**
 * description：数据访问接口的实现类之一
 * @author Administrator
 * @date 2022/3/21 16:23
 */
public class BaseDaoImpl implements BaseDao {
    @Override
    public List<Word> selectAllWords()  {
        List<Word> words = new ArrayList<>();
        Word word = null;
        try {
            List<String> lines = Files.readAllLines(Path.of(WORD_FILE_PATH));
            for (String line : lines) {
                word = new Word(line.split(" ")[0].toLowerCase(), line.split(" ")[1].split(":"));
                words.add(word);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //把错误信息记录到本地日志文件中,供后期维护使用...
        }
        return words;
    }

    @Override
    public List<Vocabulary> selectAllVocabularies()  {
        List<Vocabulary> vocabularies = new ArrayList<>();
        Vocabulary vocabulary = null;
        try {
            List<String> lines = Files.readAllLines(Path.of(VOCABULARY_FILE_PATH));
            for (String line : lines) {
                String[] arr = line.split("#");
                vocabulary = new Vocabulary(arr[0], arr[1].split(":"));
                if (arr.length > 2) {
                    vocabulary.setAbbreviation(arr[2]);
                }
                vocabularies.add(vocabulary);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vocabularies;
    }
}